//
//  ReleaseHomeworkViewController.m
//  TeacherPro
//
//  Created by DCQ on 2017/6/13.
//  Copyright © 2017年 ZNXZ. All rights reserved.
//发布家庭作业

#import "ReleaseHomeworkViewController.h"
#import "TZImagePickerController.h"
#import "FeedbackViewController.h"
#import "FeedbackModel.h"
#import "ReleaseStyleCell.h"
#import "ReleaseHWWebViewController.h"
#import "RecordingView.h"
#import "ReleaseCopyEditorViewCell.h"
#import "ReleaseEditContentFooterView.h"
#import "ReleaseEditMattersCell.h"
#import "AddReleaseEditMattersCell.h"
#import "ReleaseImageCell.h"
#import "ReleaseAddBookworkCell.h"
#import "ReleaseBookworkCell.h"
#import "ReleaseVoiceworkCell.h"
#import "ReleaseHeaderView.h"
#import "SessionHelper.h"
#import "SessionModel.h"
#import "UploadFileModel.h"
#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "ChooseClassViewController.h"
#import "ClassManageModel.h"
#import "lame.h"
#import "ProUtils.h"
#import "GTMBase64.h"
#import "IQKeyboardManager.h"

#import "BookcaseViewController.h"


#define  bottomHeight  FITSCALE(0)

#define MAX_IMAGE_COUNT             9
#define COLUMN_IMAGE_COUNT          4
static NSString *const ReleaseStyleCellIdentifier = @"ReleaseStyleCellIdentifier";
static NSString *const ReleaseCopyEditorViewCellIdentifier = @"ReleaseCopyEditorViewCellIdentifier";
static NSString *const ReleaseEditContentFooterViewIdentifier = @"ReleaseEditContentFooterViewIdentifier";
static NSString *const ReleaseEditMattersCellIdentifier = @"ReleaseEditMattersCellIdentifier";
static NSString *const AddReleaseEditMattersCellIdentifier = @"AddReleaseEditMattersCellIdentifier";
static NSString *const ReleaseImageCellIdentifier = @"ReleaseImageCellIdentifier";
static NSString *const ReleaseAddBookworkCellIdentifier = @"ReleaseAddBookworkCellIdentifier";
static NSString *const ReleaseBookworkCellIdentifier = @"ReleaseBookworkCellIdentifier";
static NSString *const ReleaseVoiceworkCellIdentifier = @"ReleaseVoiceworkCellIdentifier";
static NSString *const ReleaseHeaderViewIdentifier = @"ReleaseHeaderViewIdentifier";



@interface ReleaseHomeworkViewController ()<TZImagePickerControllerDelegate,ReleaseEditMattersDelegate,ChooseClassViewDelegate>
{
    
}
@property(nonatomic, assign) NSInteger selectedFeedbackIndex;
@property(nonatomic, strong) NSDictionary *selectedClassInfo;//选择发布班级数据
@property(nonatomic, strong) FeedbackModel *selectedFeedbackModel;//反馈数据
@property(nonatomic, strong) NSString  *CompletionTime;
@property(nonatomic, assign) CGFloat  itemWH;
@property(nonatomic, assign) CGFloat  margin;
@property(nonatomic, assign) BOOL  isTextView;//事项 和文本切换 YES 表示当前是文本， NO 表示显示事项
@property(nonatomic, assign) ReleaseEditContentFooterViewType chooseButtonType;//选中的发布编辑内容


@property(nonatomic, strong) NSMutableArray *selectedBooks;//书本数据
@property(nonatomic, strong) NSIndexPath *selectedBookIndex;//删除哪本书的标记
@property (nonatomic, strong) NSMutableArray *mattersCellHeights;//事项高度

@property (nonatomic, copy) NSString *subjects;//没有选择书本时选择的科目
@property (nonatomic, copy) NSString *bookSubjectName;//书本的科目
@property (nonatomic, strong) NSDictionary * addBookDic;
@end

@implementation ReleaseHomeworkViewController
- (instancetype)initWithData:(NSDictionary *)userInfo{
    self = [super init];
    if (self) {
        
        self.addBookDic = userInfo;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setNavigationItemTitle:@"布置作业"];
    self.CompletionTime = [self getTodayDate];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.view.backgroundColor = project_background_gray;
    [self initData];
//    [self initBottomView];
    [self registerCell];
    [self setupNavigationRightbar];
    self.tableView.separatorColor = [UIColor clearColor];
    self.contentType = @"00";
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addHomework:) name:BOOK_HOMEWORK_ADD_NEW object:nil];
    
    if (self.addBookDic) {
        NSString * content = self.addBookDic[@"content"];
        if (!self.bookSubjectName) {
            NSDictionary * json = [NSJSONSerialization JSONObjectWithData:[content dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
            self.bookSubjectName = json[@"subjectName"];
        }
        [self.selectedBooks addObject:content];
        [self updateTableView];
    }
}


- (void) setupNavigationRightbar{
    UIButton * releaseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [releaseBtn setTitle:@"发布" forState:UIControlStateNormal];
    [releaseBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    
    [releaseBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal ];
    [releaseBtn addTarget:self action:@selector(releaseAction:) forControlEvents:UIControlEventTouchUpInside];
    [releaseBtn setFrame:CGRectMake(0, 5, 40,60)];
 
    releaseBtn.titleLabel.font = fontSize_15;
  

    UIBarButtonItem * rightBar = [[UIBarButtonItem alloc]initWithCustomView:releaseBtn];
    self.navigationItem.rightBarButtonItem = rightBar;
    
}
- (NSString *)getTodayDate{
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd 23:59"];
    NSDate* date = [NSDate date];
    NSString* dateString = [formatter stringFromDate:date];
    return dateString;
    
}
- (UITableViewStyle )getTableViewStyle{
    
    return UITableViewStyleGrouped;
}

- (void)initData{
    
    [[NSUserDefaults standardUserDefaults]  removeObjectForKey:SAVE_RELEASEHOMEWORKCLASS];
    self.selectedFeedbackIndex = -1;
    self.inputContentArrays = [NSMutableArray array];
    self.selectedVoice =  [NSMutableArray array];
    self.selectedBooks = [NSMutableArray array];
    self.isTextView = YES;
    self.chooseButtonType = ReleaseEditContentFooterViewType_textViewButton;
    self.mattersCellHeights = [NSMutableArray array];
}
- (void)initBottomView{
    
//    UIView * bottomView = [[UIView alloc]initWithFrame:CGRectMake(0,  self.view.frame.size.height-bottomHeight, self.view.frame.size.width, bottomHeight)];
//    [bottomView setBackgroundColor:[UIColor whiteColor]];
//    [self.view addSubview:bottomView];
//    
//    UIButton * releaseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [releaseBtn setTitle:@"发布" forState:UIControlStateNormal];
//    [releaseBtn setBackgroundColor:project_main_blue];
//    [releaseBtn addTarget:self action:@selector(releaseAction:) forControlEvents:UIControlEventTouchUpInside];
//    [releaseBtn setFrame:CGRectMake(20, 5, self.view.frame.size.width -40, bottomHeight- 10)];
//    releaseBtn.layer.cornerRadius = (bottomHeight- 10)/2;
//    releaseBtn.layer.masksToBounds =  YES;
//    releaseBtn.titleLabel.font = fontSize_15;
//    [bottomView addSubview:releaseBtn];
    
}
-(void)registerCell{
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ReleaseStyleCell class])  bundle:nil] forCellReuseIdentifier:ReleaseStyleCellIdentifier];
    //
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ReleaseCopyEditorViewCell class])  bundle:nil] forCellReuseIdentifier:ReleaseCopyEditorViewCellIdentifier];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ReleaseEditContentFooterView class])  bundle:nil]  forHeaderFooterViewReuseIdentifier:ReleaseEditContentFooterViewIdentifier];
    
    [self.tableView registerClass: [ReleaseEditMattersCell class]  forCellReuseIdentifier:ReleaseEditMattersCellIdentifier];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([AddReleaseEditMattersCell class])  bundle:nil] forCellReuseIdentifier:AddReleaseEditMattersCellIdentifier];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ReleaseImageCell  class]) bundle:nil]  forCellReuseIdentifier:ReleaseImageCellIdentifier];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ReleaseAddBookworkCell class]) bundle:nil] forCellReuseIdentifier:ReleaseAddBookworkCellIdentifier];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ReleaseBookworkCell class]) bundle:nil]  forCellReuseIdentifier:ReleaseBookworkCellIdentifier];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ReleaseVoiceworkCell class]) bundle:nil]  forCellReuseIdentifier:ReleaseVoiceworkCellIdentifier];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ReleaseHeaderView  class])  bundle:nil]  forHeaderFooterViewReuseIdentifier:ReleaseHeaderViewIdentifier];
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 5;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSInteger row ;
    if (section ==  ReleaseHomeworkSectionType_complete) {
        row = 3 ;
    }else if (section ==  ReleaseHomeworkSectionType_contentTab){
        if (self.isTextView) {
            row = 1;
        }else{
            row = [self.inputContentArrays count] + ([self.inputContentArrays count]>0?1:2);
        }
    }else if(section ==  ReleaseHomeworkSectionType_images){
        
        row = 1;
    }else if(section ==  ReleaseHomeworkSectionType_voice){
        
        row = [self.selectedVoice count];
    }else if(section ==  ReleaseHomeworkSectionType_books){
        row = [self.selectedBooks count]+1;
    }else
        row = 0;
    return row;
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat height =   FITSCALE(44);
    if (indexPath.section ==ReleaseHomeworkSectionType_contentTab) {
        if (self.isTextView) {
            height =   FITSCALE(100);
        }else
        {
            if([self.mattersCellHeights count] >= indexPath.row+1){
                
                height  =  FITSCALE(MAX(50.0,[self.mattersCellHeights[indexPath.row] floatValue] ));
            }else{
                
                height = FITSCALE(50.0);
            }
            
        }
        
        
    }else if (indexPath.section == ReleaseHomeworkSectionType_images){
        self.margin = 4;
        NSInteger tepColumn = 4;
        self.itemWH = (self.view.frame.size.width - 2 *  self.margin - 4) / tepColumn -  self.margin;
        
#warning 待优化
        if([self.selectedPhotos count] ==0){
            height = 0;
        } else if ([self.selectedPhotos count]>0 &&[self.selectedPhotos count] <5 ) {
           height = self.itemWH +20;
        }else if ( [self.selectedPhotos count] >=5 &&[self.selectedPhotos count]<9){
           height = (self.itemWH +10)* 2 ;
        }else if([self.selectedPhotos count] ==9){
          height = (self.itemWH + 10) * 3;
        }else{
        
            height = 0;
        }
        
    }else if(indexPath.section ==  ReleaseHomeworkSectionType_voice){
        
        height =  FITSCALE(40);
    }else if (indexPath.section == ReleaseHomeworkSectionType_books)
        
    {
        if ([self.selectedBooks count] == indexPath.row) {
            height = FITSCALE(70);
        }else
            height = FITSCALE(130);
        
    }
    
    return height;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell * cell;
    
    if (indexPath.section == ReleaseHomeworkSectionType_complete) {
        
        ReleaseStyleCell * tempCell = [tableView dequeueReusableCellWithIdentifier:ReleaseStyleCellIdentifier ];
        ReleaseStyle style ;
        NSString * detail = nil;
        switch (indexPath.row) {
            case ReleaseStyle_ReleaseGrade:{
                style = ReleaseStyle_ReleaseGrade;
                //有选中的班级
                if (self.selectedClassInfo) {
                    detail = [self.selectedClassInfo allKeys][0];
                    NSString * className = [self getChooseClassName];
                    detail = [NSString stringWithFormat:@"%@ %@",detail, className];
                }
            }
                break;
            case ReleaseStyle_ReleaseFeedback:{
                style = ReleaseStyle_ReleaseFeedback;
                detail =  self.selectedFeedbackModel.name;
            }
                break;
            case ReleaseStyle_ReleaseCompleteDate:
                style = ReleaseStyle_ReleaseCompleteDate;
                detail = self.CompletionTime ;
                break;
                
            default:
                style = ReleaseStyle_Normal;
                break;
        }
        
        [tempCell setupReleaseHomeworkStyle:style withDetail:detail];
        tempCell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell = tempCell;
        
    }else if (indexPath.section == ReleaseHomeworkSectionType_contentTab){
        if (self.isTextView) {
            ReleaseCopyEditorViewCell * inputCell = [tableView dequeueReusableCellWithIdentifier:ReleaseCopyEditorViewCellIdentifier  ];
            [inputCell setupCopyEditor:[self.inputContentArrays componentsJoinedByString:@"\n"]];
            WEAKSELF
            inputCell.inputBlock = ^(NSMutableArray *inputContents) {
                
                STRONGSELF
                [strongSelf.inputContentArrays removeAllObjects];
                if ([inputContents count] >0) {
                     [strongSelf.inputContentArrays addObjectsFromArray: inputContents];
                }
               
            };
             inputCell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell = inputCell;
        }else{
            
            NSInteger  count ;
            if ([self.inputContentArrays count]>0) {
                count = [self.inputContentArrays count];
            }else{
                count = 1;
            }
            
            if (indexPath.row == count) {
                
                AddReleaseEditMattersCell  * addCell = [tableView dequeueReusableCellWithIdentifier:AddReleaseEditMattersCellIdentifier ];
                addCell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell = addCell;
            }else{
                ReleaseEditMattersCell  * mattersCell = [tableView dequeueReusableCellWithIdentifier:ReleaseEditMattersCellIdentifier ];
                mattersCell.selectionStyle = UITableViewCellSelectionStyleNone;
                if ([self.inputContentArrays count] >0) {
                    [mattersCell setupContentInfo:self.inputContentArrays[indexPath.row] withRow:indexPath.row];
                }else{
                    [mattersCell setupContentInfo:nil withRow:indexPath.row];
                }
                
                mattersCell.expandableTableView = self.tableView;
                cell = mattersCell;
            }
        }
        
    }else if (indexPath.section == ReleaseHomeworkSectionType_images){
        ReleaseImageCell * imagesCell = [tableView dequeueReusableCellWithIdentifier:
                                         ReleaseImageCellIdentifier];
        imagesCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [imagesCell setupReleaseImageCellPhotos:self.selectedPhotos withAssets:self.selectedAssets];
        imagesCell.deleteBlock = ^(UIButton *btn) {
            [self deleteBtnClik:btn];
        };
        imagesCell.lookImageBlock = ^(NSIndexPath *index) {
            [self lookImageDetail:index];
        };
        imagesCell.backgroundColor = [UIColor whiteColor];
        cell = imagesCell;
    }else if(indexPath.section == ReleaseHomeworkSectionType_voice){
        ReleaseVoiceworkCell * voiceworkCell = [tableView dequeueReusableCellWithIdentifier:ReleaseVoiceworkCellIdentifier  ];
        voiceworkCell.deleteBlock = ^{
            [self deleteVoiceAction];
        };
        voiceworkCell.selectionStyle = UITableViewCellSelectionStyleNone;
        [voiceworkCell updateVoice:self.selectedVoice[indexPath.row][@"urlCaf"]];
        cell = voiceworkCell ;
        
        
    }else if(indexPath.section == ReleaseHomeworkSectionType_books){
        if (indexPath.row < [self.selectedBooks count]) {
            ReleaseBookworkCell * bookworkCell = [tableView dequeueReusableCellWithIdentifier:ReleaseBookworkCellIdentifier];
            bookworkCell.selectionStyle = UITableViewCellSelectionStyleNone;
            bookworkCell.index = indexPath;
            bookworkCell.deleteBlock = ^(NSIndexPath *index) {
                [self deleteBookwork:index];
            };
            
            [bookworkCell setupBookworkInfo:self.selectedBooks[indexPath.row]];
            cell = bookworkCell ;
        }else  if (indexPath.row == [self.selectedBooks count]) {
            ReleaseAddBookworkCell * addbook = [tableView dequeueReusableCellWithIdentifier:ReleaseAddBookworkCellIdentifier ];
            WEAKSELF
            addbook.addBookBlock = ^{
                STRONGSELF
                [strongSelf addNewBookDecorateHomework];
            };
            addbook.selectionStyle = UITableViewCellSelectionStyleNone;
            cell = addbook ;
        }
    }
    
    return cell;
}

- ( UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    NSString * headerTitle = @"";
    
    ReleaseHeaderView * headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:ReleaseHeaderViewIdentifier];
    headerView.hidden = YES;
    
    if (section == ReleaseHomeworkSectionType_images) {
        if ([self.selectedPhotos count] > 0) {
            headerTitle = [NSString stringWithFormat:@"已添加%zd张图片",self.selectedPhotos.count];
            headerView.hidden = NO;
            headerView.titleLabel.hidden = NO;
            headerView.titleLabel.text = headerTitle;
        }
        headerView.iconImgV.hidden = YES;
        headerView.iconTitleLabel.hidden = YES;
        headerView.iconlineView.hidden = YES;
        headerView.topLineView.hidden = YES;
    }else if (section == ReleaseHomeworkSectionType_voice ){
        if ([self.selectedVoice  count] >0) {
            headerTitle =  @"已添加1条语音" ;
            headerView.hidden = NO;
             headerView.titleLabel.hidden = NO;
            headerView.titleLabel.text = headerTitle;
        }
        headerView.iconImgV.hidden = YES;
        headerView.iconTitleLabel.hidden = YES;
        headerView.iconlineView.hidden = YES;
        headerView.topLineView.hidden = YES;
    }else if (section == ReleaseHomeworkSectionType_books){
        headerTitle = @"书本作业";
        headerView.hidden = NO;
 
        headerView.titleLabel.hidden = YES;
        headerView.iconImgV.hidden = NO;
        headerView.iconTitleLabel.hidden = NO;
        headerView.iconlineView.hidden = YES;
         headerView.topLineView.hidden = NO;
        headerView.iconTitleLabel.text = headerTitle;
    }
    
    return headerView;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView * footerView = [UIView new];
    if (section == ReleaseHomeworkSectionType_contentTab) {
        ReleaseEditContentFooterView * editContentFooterView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:  ReleaseEditContentFooterViewIdentifier];
        WEAKSELF
        editContentFooterView.buttonsBlock = ^(ReleaseEditContentFooterViewType type) {
            STRONGSELF
            strongSelf.chooseButtonType = type;
            if (type == ReleaseEditContentFooterViewType_voiceButton) {
                
                [self voiceAction];
            }else if (type == ReleaseEditContentFooterViewType_photoButton){
                [self pushPickerAction];
                
            }else if (type == ReleaseEditContentFooterViewType_todoButton){
                
                [self todoAction];
            }else if (type == ReleaseEditContentFooterViewType_textViewButton){
                
                [self textViewAction];
            }
        };
        [editContentFooterView buttonSelectedTag:self.chooseButtonType];
        
//        editContentFooterView.backgroundColor = [UIColor redColor];
        footerView = editContentFooterView;
    }
    return footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    CGFloat headerHeight = 0.00000001;
    if (section == ReleaseHomeworkSectionType_complete) {
        headerHeight =  FITSCALE(15) ;
    } else if (section == ReleaseHomeworkSectionType_images) {
        headerHeight = [self.selectedPhotos count]>0 ?  FITSCALE(40)  :headerHeight;
    }else if ( section == ReleaseHomeworkSectionType_voice){
        headerHeight = [self.selectedVoice count]>0 ?  FITSCALE(40)  :headerHeight;
    }else if (section == ReleaseHomeworkSectionType_books){
        headerHeight =   FITSCALE(44) ;
    }
    return headerHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    CGFloat footerHeight =  0.0001;
    if (section == ReleaseHomeworkSectionType_contentTab) {
        footerHeight = FITSCALE(44);
    }else if (section == ReleaseHomeworkSectionType_complete){
        
        footerHeight = 7;
    }
    
    return footerHeight;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.section ==  ReleaseHomeworkSectionType_complete) {
        if (indexPath.row == ReleaseStyle_ReleaseFeedback) {
            [self gotoFeedbackVC];
        }else if (indexPath.row == ReleaseStyle_ReleaseCompleteDate){
            [self showCompletionAlertView];
        }else if (indexPath.row == ReleaseStyle_ReleaseGrade){
            [self gotoChooseClass];
        }
        
    }else if (indexPath.section ==  ReleaseHomeworkSectionType_books){
        
        if (self.selectedBooks.count == 0 ||indexPath.row == self.selectedBooks.count ) {
            [self addNewBookDecorateHomework];
        }
    }else if (indexPath.section ==  ReleaseHomeworkSectionType_contentTab){
        NSInteger row = [self.inputContentArrays count] + ([self.inputContentArrays count]>0?1:2);
        if (!self.isTextView ) {
            if ( row>2 && indexPath.row == row - 1 ) {
                if ([self.inputContentArrays lastObject] ) {
                    NSString * str = [self.inputContentArrays lastObject];
                    if (str.length >0) {
                        [self addItemDecorateHomework];
                    }
                }
                
            }else if (row ==2 && [self.inputContentArrays count]==1){
                [self addItemDecorateHomework];
            }
        }
    }
    
}


- (void)tableView:(UITableView *)tableView updatedHeight:(CGFloat)height atIndexPath:(NSIndexPath *)indexPath
{
    if ([self.mattersCellHeights count] >= indexPath.row+1) {
        [self.mattersCellHeights replaceObjectAtIndex:indexPath.row withObject:@(height) ];
    }else{
        
        [self.mattersCellHeights addObject:@(height)];
    }
    
}

- (void)tableView:(UITableView *)tableView updatedText:(NSString *)text atIndexPath:(NSIndexPath *)indexPath
{
    
    if ([self.inputContentArrays count]>=indexPath.row+1) {
        [self.inputContentArrays replaceObjectAtIndex:indexPath.row withObject:text];
    }else{
        if ([self.inputContentArrays count ]== 0) {
            [self.inputContentArrays addObject:text];
        }else
            [self.inputContentArrays addObject:[NSString stringWithFormat:@"\n%@",text]];
    }
    
}
- (void)textViewShouldReturn{
    [self addItemDecorateHomework];
}
#pragma mark
- (NSString *)getChooseClassId{
    
    
    NSString * classId = @"";
    NSArray * selectedClassArray  = [self.selectedClassInfo allValues][0];
    for (ClassManageModel * model in  selectedClassArray) {
        if ([classId length] <=0) {
            classId = model.clazzId;
        }else{
            
            classId = [classId stringByAppendingString:[NSString stringWithFormat:@",%@",model.clazzId]];
        }
    }
    
    classId = [NSString stringWithFormat:@"%@",classId];
    
    return  classId;
}

- (NSString *)getChooseClassName{
    
    
    NSString * className = @"";
    NSArray * selectedClassArray  = [self.selectedClassInfo allValues][0];
    for (ClassManageModel * model in  selectedClassArray) {
        if ([className length] <=0) {
            className = model.clazzName;
        }else{
            
            className = [className stringByAppendingString:[NSString stringWithFormat:@"、%@",model.clazzName]];
        }
    }
    return className;
}
#pragma mark  touch event

- (void)gotoChooseClass{
    
    ChooseClassViewController * chooseClassVC = [[ChooseClassViewController alloc]initWithViewControllerFromeType:ViewControllerFromeType_Choose];
    chooseClassVC.chooseDelegate = self;
    
    [self pushViewController:chooseClassVC];
}
- (void)gotoFeedbackVC{
    
    FeedbackViewController * feedbackVC = [[FeedbackViewController alloc]initWithIndex:self.selectedFeedbackIndex];
    WEAKSELF
    feedbackVC.feedbackBlock = ^(FeedbackModel *model, NSInteger  index){
        STRONGSELF
        strongSelf.selectedFeedbackIndex = index;
        strongSelf.selectedFeedbackModel = model;
        [strongSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:ReleaseStyle_ReleaseFeedback inSection:ReleaseHomeworkSectionType_complete]] withRowAnimation:UITableViewRowAnimationNone];
    };
    [self pushViewController:feedbackVC];
}

- (void)showCompletionAlertView{
    
    NSString * title = @"完成作业时间";
    NSString * normalTime = @"";
    NSArray *items =@[
                      MMItemMake(@"取消", MMItemTypeHighlight, nil),
                      MMItemMake(@"确定", MMItemTypeHighlight, nil)
                      ];
    WEAKSELF
    AlertView * alert =[[AlertView alloc]initWithCompletionTimeTitle:title normalTime:normalTime items:items handler:^(NSString *text) {
//        NSLog(@"%@===选择的完成作业时间",text);
        STRONGSELF
        strongSelf.CompletionTime = text;
        [strongSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:ReleaseStyle_ReleaseCompleteDate inSection:ReleaseHomeworkSectionType_complete]] withRowAnimation:UITableViewRowAnimationNone];
    }];
    [alert show];
}
#pragma mark - TZImagePickerController

- (void)pushImagePickerController {
    if ( MAX_IMAGE_COUNT  <= 0) {
        return;
    }
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:MAX_IMAGE_COUNT columnNumber:COLUMN_IMAGE_COUNT delegate:self pushPhotoPickerVc:YES];
    
    
#pragma mark - 四类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = NO;
    
    if (MAX_IMAGE_COUNT > 1) {
        // 1.设置目前已经选中的图片数组
        imagePickerVc.selectedAssets = _selectedAssets; // 目前已经选中的图片数组
    }
    imagePickerVc.allowTakePicture = YES; // 在内部显示拍照按钮
    
    // 2. Set the appearance
    // 2. 在这里设置imagePickerVc的外观
    // imagePickerVc.navigationBar.barTintColor = [UIColor greenColor];
    // imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    // imagePickerVc.oKButtonTitleColorNormal = [UIColor greenColor];
    // imagePickerVc.navigationBar.translucent = NO;
    
    // 3. Set allow picking video & photo & originalPhoto or not
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.allowPickingGif = NO;
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = NO;
    
    // imagePickerVc.minImagesCount = 3;
    // imagePickerVc.alwaysEnableDoneBtn = YES;
    
    // imagePickerVc.minPhotoWidthSelectable = 3000;
    // imagePickerVc.minPhotoHeightSelectable = 2000;
    
    /// 5. Single selection mode, valid when maxImagesCount = 1
    /// 5. 单选模式,maxImagesCount为1时才生效
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.allowCrop = NO;
    imagePickerVc.needCircleCrop = NO;
    imagePickerVc.circleCropRadius = 100;
    /*
     [imagePickerVc setCropViewSettingBlock:^(UIView *cropView) {
     cropView.layer.borderColor = [UIColor redColor].CGColor;
     cropView.layer.borderWidth = 2.0;
     }];*/
    
    //imagePickerVc.allowPreview = NO;
#pragma mark - 到这里为止
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
    }];
    [imagePickerVc setNaviBgColor:project_main_blue];
    [imagePickerVc setNaviTitleFont:fontSize_18];
    
    [imagePickerVc setDoneBtnTitleStr:@"确定"];
    
    [imagePickerVc setOKButtonTitleColorNormal:[UIColor whiteColor]];
    [imagePickerVc setOKButtonTitleColorDisabled:[UIColor lightGrayColor]];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    
}



#pragma mark - TZImagePickerControllerDelegate

/// User click cancel button
/// 用户点击了取消
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker {
    // NSLog(@"cancel");
}

// The picker should dismiss itself; when it dismissed these handle will be called.
// If isOriginalPhoto is YES, user picked the original photo.
// You can get original photo with asset, by the method [[TZImageManager manager] getOriginalPhotoWithAsset:completion:].
// The UIImage Object in photos default width is 828px, you can set it by photoWidth property.
// 这个照片选择器会自己dismiss，当选择器dismiss的时候，会执行下面的代理方法
// 如果isSelectOriginalPhoto为YES，表明用户选择了原图
// 你可以通过一个asset获得原图，通过这个方法：[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]
// photos数组里的UIImage对象，默认是828像素宽，你可以通过设置photoWidth属性的值来改变它
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    _selectedPhotos = [NSMutableArray arrayWithArray:photos];
    _selectedAssets = [NSMutableArray arrayWithArray:assets];
    //    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    
    // _tableView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
    
    // 1.打印图片名字
    //    [self printAssetsName:assets];
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:ReleaseHomeworkSectionType_images] withRowAnimation:UITableViewRowAnimationNone];
}

//预览图
- (void)lookImageDetail:(NSIndexPath *)indexPath{

    id asset = _selectedAssets[indexPath.row];
    BOOL isVideo = NO;
    if ([asset isKindOfClass:[PHAsset class]]) {
        PHAsset *phAsset = asset;
        isVideo = phAsset.mediaType == PHAssetMediaTypeVideo;
    } else if ([asset isKindOfClass:[ALAsset class]]) {
        ALAsset *alAsset = asset;
        isVideo = [[alAsset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo];
    }
      // preview photos / 预览照片
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_selectedAssets selectedPhotos:_selectedPhotos index:indexPath.row];
        imagePickerVc.maxImagesCount = [_selectedAssets count];
        imagePickerVc.allowPickingOriginalPhoto = NO;
        imagePickerVc.isSelectOriginalPhoto = NO;
        [imagePickerVc setNaviBgColor:project_main_blue];
        [imagePickerVc setNaviTitleFont:fontSize_18];
    
        [imagePickerVc setDoneBtnTitleStr:@"确定"];
    
        [imagePickerVc setOKButtonTitleColorNormal:[UIColor whiteColor]];
        [imagePickerVc setOKButtonTitleColorDisabled:[UIColor lightGrayColor]];
    
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            _selectedPhotos = [NSMutableArray arrayWithArray:photos];
            _selectedAssets = [NSMutableArray arrayWithArray:assets];
        
            [self reloadImages];
        }];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
    
}
#pragma mark - Click Event

- (void)reloadImages{
    
    NSIndexSet * indexset = [NSIndexSet indexSetWithIndex:ReleaseHomeworkSectionType_images];
    [self.tableView reloadSections:indexset withRowAnimation:UITableViewRowAnimationNone];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:ReleaseHomeworkSectionType_images] atScrollPosition:UITableViewScrollPositionNone animated:NO];
}
- (void)deleteVoiceAction{
    [self.selectedVoice removeAllObjects];
    self.totalLength =  0;
    
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex: ReleaseHomeworkSectionType_voice] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)pushPickerAction{
    
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex: ReleaseHomeworkSectionType_contentTab] withRowAnimation:UITableViewRowAnimationNone];
    [self pushImagePickerController];
}
- (void)voiceAction{
    
    if ([self.selectedVoice count] >0) {
        NSString * title = @"温馨提示";
        NSString * content = @"已经有录音了,请先删除当前录音";
        NSArray *items =
        @[MMItemMake(@"确定", MMItemTypeHighlight, nil)
          ];
        [self showNormalAlertTitle:title content:content items:items block:nil];
        
    }else{
        //语音
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex: ReleaseHomeworkSectionType_contentTab] withRowAnimation:UITableViewRowAnimationNone];
        RecordingView *recording= [[RecordingView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        WEAKSELF
        recording.saveRecordingBlock = ^(NSURL * recordingUrl,NSURL *mp3Url, NSInteger totalLength){
            
            if ([self.selectedVoice count] == 0) {
                [self.selectedVoice addObject:@{@"urlCaf":recordingUrl,@"urlMp3":mp3Url}];
            }
            weakSelf.totalLength = totalLength;
            [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex: ReleaseHomeworkSectionType_voice] withRowAnimation:UITableViewRowAnimationNone];
            [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:ReleaseHomeworkSectionType_voice] atScrollPosition:UITableViewScrollPositionNone animated:YES];
            
        };
        [[UIApplication sharedApplication].keyWindow  addSubview:recording];
        
    }
}

/**
事项
*/
- (void)todoAction{
    //事项
    self.isTextView = NO;
     self.contentType = @"01";
    
    if ([self.inputContentArrays count] >0) {
        [self.mattersCellHeights removeAllObjects];
        for (NSString * inputTodoItem in self.inputContentArrays) {
            CGFloat textViewW =  IPHONE_WIDTH - 100;
            CGFloat itemHeight =   FITSCALE(50);
             CGFloat tempHeight = [self heightForString:inputTodoItem andWidth: textViewW];
            
            if (tempHeight >FITSCALE(50)) {
                itemHeight = tempHeight;
            }
            [self.mattersCellHeights addObject:@(itemHeight)];
        }
    }
    [self.tableView reloadData];
}
/**
 @method 获取指定宽度width,字体大小fontSize,字符串value的高度
 @param value 待计算的字符串
 @param fontSize 字体的大小
 @param Width 限制字符串显示区域的宽度
 @result float 返回的高度
 */
- (float) heightForString:(NSString *)value andWidth:(float)width{
    //获取当前文本的属性
//    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:value];
 
//    NSRange range = NSMakeRange(0, attrStr.length);
    // 获取该段attributedString的属性字典
//    NSDictionary *dic = [attrStr attributesAtIndex:0 effectiveRange:&range];
     NSDictionary *dic = @{NSFontAttributeName:fontSize_13};
    // 计算文本的大小
    CGSize sizeToFit = [value boundingRectWithSize:CGSizeMake(width - 16.0, MAXFLOAT) // 用于计算文本绘制时占据的矩形块
                                           options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading // 文本绘制时的附加选项
                                        attributes:dic        // 文字的属性
                                           context:nil].size; // context上下文。包括一些信息，例如如何调整字间距以及缩放。该对象包含的信息将用于文本绘制。该参数可为nil
    return sizeToFit.height + 16.0;
}


- (void)textViewAction{
    //文字
    self.isTextView = YES;
    self.contentType = @"00";
    [self.tableView reloadData];
}



- (void)deleteBtnClik:(UIButton *)sender {
    
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:ReleaseHomeworkSectionType_images] withRowAnimation:UITableViewRowAnimationNone];
    
    
}

- (void)deleteBookwork:(NSIndexPath *)index{
 
    
    if ([self.selectedBooks count]>= index.row) {
        NSData * data = [ self.selectedBooks[index.row] dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; ;
        NSString * content =[NSString stringWithFormat:@"确定删除\n%@",dic[@"name"]];
        
        self.selectedBookIndex = index;
        WEAKSELF
        [self showNormalAlertTitle:@"温馨提示" content:content items:nil block:^(NSInteger index) {
            STRONGSELF
            [self.selectedBooks removeObjectAtIndex:strongSelf.selectedBookIndex.row];
         
            [self.tableView deleteRowsAtIndexPaths:@[strongSelf.selectedBookIndex]  withRowAnimation:UITableViewRowAnimationBottom];
            if (self.selectedBooks.count == 0) {
                self.bookSubjectName = nil;
                
            }
        }];
      
    }
}

//添加书本作业
- (void)addNewBookDecorateHomework{
    
    //htm 5
//    [self gotoHtml5Homework];
    
    NSString * subjectName = self.bookSubjectName;
    
    //原生
    BookcaseViewController *bookcaseVC = [[BookcaseViewController alloc]initWithbzSubjectName:subjectName];
    [self pushViewController:bookcaseVC];
}

- (void)gotoHtml5Homework{

    ReleaseHWWebViewController * webView = [[ReleaseHWWebViewController alloc]init];
    WEAKSELF
    webView.chooseBookBlock = ^(NSString * content){
        STRONGSELF
        [strongSelf.selectedBooks addObject:content];
        [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:[strongSelf.selectedBooks count]-1 inSection:ReleaseHomeworkSectionType_books]]  withRowAnimation:UITableViewRowAnimationBottom];
        [strongSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[strongSelf.selectedBooks count] inSection:ReleaseHomeworkSectionType_books] atScrollPosition:UITableViewScrollPositionNone animated:YES];
    };
    
    [self pushViewController:webView];
}
- (void)addItemDecorateHomework {
    
    [self.inputContentArrays addObject:@""];
    [self.tableView  reloadSections:[NSIndexSet indexSetWithIndex: ReleaseHomeworkSectionType_contentTab] withRowAnimation:UITableViewRowAnimationNone];
    NSInteger row = [self.inputContentArrays count]-1;
    ReleaseEditMattersCell * cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:ReleaseHomeworkSectionType_contentTab]];
    [cell.textView becomeFirstResponder];
    
}
- (void)releaseAction:(UIButton *)sender{
    sender.selected = !sender.selected;
    sender.enabled = NO;
    if (sender.selected) {
        [self releaseHomework];
    }
    
}


- (void)releaseHomework{

    [[IQKeyboardManager sharedManager] resignFirstResponder];
    //清空上次选择的上传成功后的数据
    self.uplaodImageModel = nil;
    self.uplaodAudioModel = nil;
    NSString *  clazzIds = [self getChooseClassId];//必传
    if ([clazzIds length] <=0) {
        NSString * title = @"温馨提示";
        NSString * content = @"请您选择布置作业的班级";
        NSArray *items =
        @[MMItemMake(@"确定", MMItemTypeHighlight, nil
                     )];
        [self showNormalAlertTitle:title content:content items:items block:nil];
        
        [self enabldSenderBtn];
        return;
    }
    
    
    NSString *  endTime= self.CompletionTime;//必传
    
    if ([endTime length] <=0) {
        NSString * title = @"温馨提示";
        NSString * content = @"请您选择布置作业的完成时间";
        NSArray *items =
        @[MMItemMake(@"确定", MMItemTypeHighlight, nil
                     )];
        [self showNormalAlertTitle:title content:content items:items block:nil];
        [self enabldSenderBtn];
        return;
    }
    
    if ([self.selectedVoice count]== 0 && [self.selectedAssets count] ==0 && [self.inputContentArrays count]== 0 &&[self.selectedBooks count]== 0) {
        NSString * title = @"温馨提示";
        NSString * content = @"请您布置作业内容";
        NSArray *items =
        @[MMItemMake(@"确定", MMItemTypeHighlight, nil
                     )];
        [self showNormalAlertTitle:title content:content items:items block:nil];
        [self enabldSenderBtn];
        return;
    }
    if ([self.selectedBooks count]== 0 && !self.subjects) {
        
        [self showSubjectsAlert];
        [self enabldSenderBtn];
        return;
    }
    if ([self.selectedAssets count] >0) {
        [self uploadImgV];
    }else if ([self.selectedAssets count] == 0 && [self.selectedVoice count] >0){
        
        [self uploadAudio];
    }else if ([self.selectedVoice count] == 0 && [self.selectedAssets count] ==0){
        
        [self requestReleaseHomework];
    }

}

- (void)enabldSenderBtn{

    UIButton * releaseBtn = self.navigationItem.rightBarButtonItem.customView;
    releaseBtn.selected = NO;
    releaseBtn.enabled = YES;
}
#pragma mark

- (void)uploadImgV{
    
    NSURL * url = [NSURL URLWithString:Request_NameSpace_upload_internal];
    NSDictionary * requestHeaders ;
    if ([[SessionHelper sharedInstance] checkSession]) {
        requestHeaders =@{@"auth-token":(SessionModel *)[[SessionHelper sharedInstance] getAppSession].token};
    }
    NSMutableDictionary * fileDic = [NSMutableDictionary dictionary];
    for (int i =0;i<[self.selectedAssets count] ;i++) {
        UIImage * image = self.selectedPhotos[i];
        
        
        NSString * fileName = @"";
        if (iOS8Later) {
            
            PHAsset * asset = self.selectedAssets[i];
            fileName= asset.localIdentifier;
            
//            NSArray *resources = [PHAssetResource assetResourcesForAsset:asset];
//            fileName = ((PHAssetResource*)resources[0]).originalFilename;
        } else {
            ALAsset * asset = self.selectedAssets[i];
            fileName =  asset.defaultRepresentation.filename;
            
        }
        
        [fileDic setObject:image forKey: fileName];
    }
    
    if ([self.selectedAssets count] > 0) {
      
        [[NetRequestManager sharedInstance] sendUploadRequest:(NSURL *)url parameterDic:@{@"appType":@"Primary",@"busiType":@"avatar"} requestMethodType:RequestMethodType_UPLOADIMG requestTag:NetRequestType_HomeworkUploadImage  delegate:self fileDic:fileDic];
    }
    
    
}

- (void)uploadAudio{
    
   for (int i =0;i<[self.selectedVoice count] ;i++) {
        [self  transformCAFToMP3UrlCaf:self.selectedVoice[i][@"urlCaf"] withMp3Url:self.selectedVoice[i][@"urlMp3"]];
    }
    
    
}

//
- (void)requestReleaseHomework{
   
    NSString *  clazzIds = [self getChooseClassId];//必传
    
    NSString *  feedback = @"";//可选
    NSString *  text = @"";//可传
    NSString *  photos= @"";//可传
    NSString *  sound= @"";//可传
    
    NSString *  endTime= [NSString stringWithFormat:@"%@:59",self.CompletionTime];//必传
    
    
    NSString *  bookHomeworks= @"";//可传
    
    NSMutableDictionary  *requestParameterDic = [NSMutableDictionary dictionary];
    NSDictionary * mustDic =  @{
                                @"clazzIds":clazzIds,
                                @"endTime":endTime,
                                
                                };
    [requestParameterDic addEntriesFromDictionary:  mustDic];
    
    if (self.selectedFeedbackModel) {
        feedback = self.selectedFeedbackModel.id;
        [requestParameterDic addEntriesFromDictionary:@{@"feedback":feedback}];
    }
    
    if ([self.inputContentArrays count] > 0) {
        
        if ([self.contentType  isEqualToString:@"00"]) {
            text = [self.inputContentArrays componentsJoinedByString:@"\n"];
            [requestParameterDic addEntriesFromDictionary:@{@"text":text}];
        }else if ([self.contentType isEqualToString:@"01"]){
            
            for (int i = 0; i<[self.inputContentArrays count]; i++) {
                NSString * newline = @"\n";
                if (i ==0) {
                    newline = @"";
                }
              text = [text stringByAppendingString:[NSString stringWithFormat:@"%@%zd、%@",newline,i+1,self.inputContentArrays[i]]] ;
                
            }
            
            [requestParameterDic addEntriesFromDictionary:@{@"text":text}];
        }
        
    }
    if (self.uplaodAudioModel) {
        sound = [self.uplaodAudioModel.visitUrls allValues][0];
        [requestParameterDic addEntriesFromDictionary:@{@"sound": sound}];
    }
    if (self.uplaodImageModel){
        for (int i =0;i<[self.selectedAssets count] ;i++) {
            
            NSString * fileName = @"";
            if (iOS8Later) {
                
                PHAsset * asset = self.selectedAssets[i];
                 fileName= asset.localIdentifier;
                if (![fileName containsString:@".jpg"]) {
                    fileName = [fileName stringByAppendingString:@".jpg"];
                }
            } else {
                ALAsset * asset = self.selectedAssets[i];
                fileName =  asset.defaultRepresentation.filename;
                
            }
            
            if ([photos length] <=0) {
                photos = [self.uplaodImageModel.visitUrls objectForKey:fileName];
            }else{
                photos = [NSString stringWithFormat:@"%@,%@",photos,[self.uplaodImageModel.visitUrls objectForKey:fileName]];
            }
            
        }
        
        [requestParameterDic addEntriesFromDictionary:@{@"photos":photos}];
    }
    if([self.selectedBooks count] >0){
        bookHomeworks =[NSString stringWithFormat:@"[%@]",[self.selectedBooks componentsJoinedByString:@","]];
        
        bookHomeworks = [bookHomeworks stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        bookHomeworks = [bookHomeworks stringByReplacingOccurrencesOfString:@" " withString:@""];
        bookHomeworks = [bookHomeworks stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        [requestParameterDic addEntriesFromDictionary:@{@"bookHomeworks":bookHomeworks}];
    }
    if (self.subjects) {
           [requestParameterDic addEntriesFromDictionary:@{@"subjectId":self.subjects}];
    }
    [self sendHeaderRequest:[NetRequestAPIManager getRequestURLStr:NetRequestType_TeacherAssignHomework] parameterDic: requestParameterDic requestMethodType:RequestMethodType_POST requestTag:NetRequestType_TeacherAssignHomework];
    
}

- (void)netRequest:(NetRequest *)request failedWithError:(NSError *)error{

    [super netRequest:request failedWithError:error];
    UIButton * releaseBtn = self.navigationItem.rightBarButtonItem.customView;
    releaseBtn.selected = NO;
    releaseBtn.enabled = YES;
}

- (void)netRequest:(NetRequest *)request successWithInfoObj:(id)infoObj{
    
    
     UIButton * releaseBtn = self.navigationItem.rightBarButtonItem.customView;
     releaseBtn.selected = NO;
     releaseBtn.enabled = YES;
    if (request.tag == NetRequestType_HomeworkUploadImage) {
        self.uplaodImageModel = [[UploadFileModel alloc]initWithDictionary:infoObj error:nil];
         [super hideHUD];
        if ([self.selectedVoice count]> 0) {
            [self uploadAudio];
        }else{
            [self requestReleaseHomework];
        }
        
    }else if (request.tag == NetRequestType_HomeworkUploadAudio){
        self.uplaodAudioModel = [[UploadFileModel alloc]initWithDictionary:infoObj error:nil];
        [super hideHUD];
        [self requestReleaseHomework];
        
    }else if (request.tag == NetRequestType_TeacherAssignHomework){
        
        [super netRequest:request successWithInfoObj:infoObj];
    }else{
       [super netRequest:request successWithInfoObj:infoObj];
    }
}



- (void)setNetworkRequestStatusBlocks{
    
    WEAKSELF
    [self setNetSuccessBlock:^(NetRequest *request, id successInfoObj) {
        STRONGSELF
        if (request.tag == NetRequestType_TeacherAssignHomework) {
            [strongSelf showAlert:TNOperationState_OK content:@"布置作业完成" block:^(NSInteger index) {
               [strongSelf backViewController];
            }];
        }
    }];
}

#pragma mark  choose Delegate
- (void)chooseClassInfo:(NSDictionary *)info{
    
    self.selectedClassInfo = info;
    NSMutableArray * tempArray = [NSMutableArray array];
    for (ClassManageModel *model in [self.selectedClassInfo allValues][0]) {
        [tempArray addObject:model.clazzId];
    }
    [[NSUserDefaults standardUserDefaults] setObject:@{[self.selectedClassInfo allKeys][0]:tempArray} forKey:SAVE_RELEASEHOMEWORKCLASS];
    [self reloadGrad];
    
}
- (void)reloadGrad{
    
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:ReleaseStyle_ReleaseGrade] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)transformCAFToMP3UrlCaf:(NSURL *)recordingUrl  withMp3Url:(NSURL *)mp3Url{
    //    NSURL* mp3FilePath = [NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingString:kMyselfRecordFile]];
    NSURL * mp3FilePath = mp3Url;
    @try {
        int read, write;
        
        FILE *pcm = fopen([[recordingUrl  absoluteString] cStringUsingEncoding:1], "rb");   //source 被转换的音频文件位置
        fseek(pcm, 4*1024, SEEK_CUR);                                                   //skip file header
        FILE *mp3 = fopen([[mp3FilePath absoluteString] cStringUsingEncoding:1], "wb"); //output 输出生成的Mp3文件位置
        
        const int PCM_SIZE = 8192;
        const int MP3_SIZE = 8192;
        short int pcm_buffer[PCM_SIZE*2];
        unsigned char mp3_buffer[MP3_SIZE];
        
        lame_t lame = lame_init();
        lame_set_in_samplerate(lame, 11025.0);
        lame_set_VBR(lame, vbr_default);
        lame_init_params(lame);
        
        do {
            read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
            if (read == 0)
                write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
            else
                write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
            
            fwrite(mp3_buffer, write, 1, mp3);
            
        } while (read != 0);
        
        lame_close(lame);
        fclose(mp3);
        fclose(pcm);
    }
    @catch (NSException *exception) {
        NSLog(@"%@",[exception description]);
        [self showAlert:TNOperationState_Fail content:@"上传音频失败,请稍后再试"];
    }
    @finally {
        
        NSLog(@"MP3生成成功: %@",mp3FilePath);
        //        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"mp3转化成功！" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        //        [alert show];
        
        [self uploadMp3];
        
        
    }
    
}

- (void)uploadMp3{
    
    NSURL * url = [NSURL URLWithString:Request_NameSpace_upload_internal];
    NSDictionary * requestHeaders ;
    if ([[SessionHelper sharedInstance] checkSession]) {
        requestHeaders =@{@"auth-token":(SessionModel *)[[SessionHelper sharedInstance] getAppSession].token};
    }
    NSMutableDictionary * fileDic = [NSMutableDictionary dictionary];
    for (int i =0;i<[self.selectedVoice count] ;i++) {
        
        
        NSURL * voiceURL = self.selectedVoice[i][@"urlMp3"];
        
        [fileDic setObject:voiceURL  forKey: kMyselfRecordFile];
    }
    
    if ([self.selectedVoice count] >0) {
        [[NetRequestManager sharedInstance] sendUploadRequest:(NSURL *)url parameterDic:@{@"appType":@"Primary",@"busiType":@"voice"} requestMethodType:RequestMethodType_UPLOADAUDIO requestTag:NetRequestType_HomeworkUploadAudio  delegate:self fileDic:fileDic];
    }
    
}

- (void)dealloc{
 
    [self setTableView:nil];
    [self setSelectedBooks:nil] ;
    [self setSelectedVoice:nil ];
    [self setSelectedBookIndex:nil];
    [self setSelectedPhotos:nil];
    [self setSelectedAssets: nil];
    [self setInputContentArrays:nil];
    [self setSelectedClassInfo:nil];
    [self setSelectedFeedbackModel:nil];
    [self  setMattersCellHeights:nil];
    [self setUplaodImageModel: nil];
    [self setUplaodAudioModel:nil];
    [self clearDelegate];
 
}

// 页面消失时候
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    ReleaseVoiceworkCell * voiceworkCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:  ReleaseHomeworkSectionType_voice] ];
    [voiceworkCell stopPlayer];
}

- (void)showSubjectsAlert{

    NSString * title = @"您布置的作业属于什么科目？";
    NSArray *  items =@[
                        MMItemMake(@"取消", MMItemTypeHighlight, nil),
                        MMItemMake(@"确定", MMItemTypeHighlight, nil)
                        ];
    AlertView * alertView = [[AlertView alloc]initWithTitle:title withSubjects:@"" items:items];
    WEAKSELF
    alertView.subjectsBlock = ^(NSString *subjects) {
        weakSelf.subjects = subjects;
        
        if ([weakSelf.selectedAssets count] >0) {
            [weakSelf uploadImgV];
            
        }else if ([self.selectedAssets count] == 0 && [self.selectedVoice count] >0){
            
            [weakSelf uploadAudio];
        }else if ([self.selectedVoice count] == 0 && [self.selectedAssets count] ==0){
            
            [weakSelf requestReleaseHomework];
        }
    };
    [alertView show];
}


- (void)addHomework:(NSNotification *)notifi{
    
   [self handleHomeworkDic:notifi.userInfo];
    
}

- (void)handleHomeworkDic:(NSDictionary *)userInfo{
    NSString * content = userInfo[@"content"];
    if (!self.bookSubjectName) {
        NSDictionary * json = [NSJSONSerialization JSONObjectWithData:[content dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
        self.bookSubjectName = json[@"subjectName"];
    }
    [self.selectedBooks addObject:content];
    [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:[self.selectedBooks count]-1 inSection:ReleaseHomeworkSectionType_books]]  withRowAnimation:UITableViewRowAnimationBottom];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.selectedBooks count] inSection:ReleaseHomeworkSectionType_books] atScrollPosition:UITableViewScrollPositionNone animated:YES];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//   self.uplaodImageModel = nil;//图片地址信息
//   self.uplaodAudioModel= nil;//音频地址信息
//   self.inputContentArrays = nil;//输入的内容
//   self.selectedVoice = nil;//录音数据
//    self.selectedPhotos = nil;//图片数据
//    self.tableView = nil;
//    self.selectedAssets = nil;
//    self.selectedClassInfo = nil;//选择发布班级数据
//    self.selectedFeedbackModel= nil;//反馈数据
//    self.CompletionTime = nil;
//
//    /// 没有网络连接需要执行的代码块
//   self.noNetworkBlock = nil; // 默认为页面显示没有网络连接的提示图
//    
//    /// 网络请求开始需要执行的代码块
//    self.startedBlock = nil;     // 默认为用HUD显示"加载中..."
//    /// 文件上传网络请求开始需要执行的代码块
//    self. startedUploadBlock = nil;     //  用HUD显示"上传..."
//    
//    
//    /// 网络请求过程需要执行的代码块
//    self.progressBlock = nil;   // 默认为nil
//    
//    /// 网络请求成功需要执行的代码块
//   self.successBlock = nil;     // 默认为nil
//    
//    
//    /// 网络请求失败需要执行的代码块
//   self.failedBlock = nil;       // 默认
    
}

- (void)backViewController
{
    
    NSArray *viewControllers = [self.navigationController viewControllers];
    
    // 根据viewControllers的个数来判断此控制器是被present的还是被push的
    if (1 <= viewControllers.count && 0 < [viewControllers indexOfObject:self])
    {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
   
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
